

import asyncio
import base64
import datetime
import cv2
from lj_tool import tool_async, tool_cache, tool_open_cv, tool_run, tool_thread, tool_ws

cv_dict = {}
cv_for = {}


async def on_msg(conn_id, msg):
    print(msg)


async def on_conn(conn_id, path):
    cv_dict[conn_id] = tool_open_cv.LJStreamCv(path[1:])
    # cv_dict[conn_id] = tool_ffmpeg.LJFfmpeg(path[1:], lj_ws.get_conn(conn_id))

    await frame_img(conn_id)


async def frame_img(conn_id):
    # await cv_dict[conn_id].start()
    frame_list = []

    def run():
        res = cv_dict[conn_id].start()
        for frame in res:
            frame_list.append(frame)
    tool_thread.run(run)

    async def send_img_interior():
        if (len(frame_list) > 0):
            await send_img(conn_id, frame_list.pop(0))
        else:
            await asyncio.sleep(0.2)

    cv_for[conn_id] = tool_run.init_new_run(send_img_interior)

    await tool_run.start_async_run(cv_for[conn_id])


@tool_cache.throttle_async("rstp_send_img", 0.2, c_args=[0])
async def send_img(conn_id, frame):
    _, img = cv2.imencode('.jpg', frame)
    await lj_ws.send(conn_id, f"data:image/jpeg;base64,{base64.b64encode(img.tobytes()).decode('utf-8')}")


def on_close(conn_id):
    print("执行关闭函数...")
    cv = cv_dict.get(conn_id)
    if cv:
        cv.stop()

    cf = cv_for[conn_id]
    if cf:
        tool_run.stop_run(cf)


lj_ws = tool_ws.LJWs(32323, on_msg, on_conn=on_conn, on_close=on_close)

lj_ws.start()
